/*
 * Copyright 2022 Institute of Software Chinese Academy of Sciences, ISRC
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import router from '@system.router';
import featureAbility from '@ohos.ability.featureAbility';
import prompt from '@ohos.prompt';
import http from '@ohos.net.http';

const serviceList = [
    {
        id: 0,
        imgUrl: 'common/images/personPic/1.png',
        text: '设置备注和标签',
        url: '',
        find_right_icon: '/common/images/findPic/find-right-icon.png'
    },
    {
        id: 1,
        imgUrl: '/common/images/personPic/2.png',
        text: '朋友权限',
        url: '',
        find_right_icon: '/common/images/findPic/find-right-icon.png'
    },
    {
        id: 2,
        imgUrl: '/common/images/personPic/3.png',
        text: '朋友圈',
        url: '',
        find_right_icon: '/common/images/findPic/find-right-icon.png'
    },
    {
        id: 3,
        imgUrl: '/common/images/personPic/4.png',
        text: '删除该好友',
        url: '',
        find_right_icon: '/common/images/findPic/find-right-icon.png'
    },
]
const personData = {
    uid:'',
    name: '小蔡同学',
    nickname:'我叫学习',
    imgUrl: '/common/images/sessionPic/img_7.png',
    area: '英国',
}

const sendList=[
            {
                'title':'发消息',
                'image':'/common/images/sendMessage.png'
            },
            {
                'title':'音视频电话',
                'image':'/common/images/videoTele.png'
            }
        ]

export default {
    data: {
        person: personData,
        serviceList: serviceList,
        sendList:sendList,
        uid: '324232',
        idx:'',
        eIdx: 0,
        mailFriendId:'',
        inBlackList:false
    },
    onInit() {
        this.idx = this.$app.$def.idx;
        this.uid = this.$app.$def.chatData[this.idx].uid
        console.info("friendDetail=====>idx"+this.idx)
        console.info("friendDetail=====>uid"+this.uid)
        this.grantPermission();
        this.mailFriendId = this.$app.$def.mailFriendId;
        console.info('friendDetail=====>this.mailFriendId: ' + this.mailFriendId )
        //群聊详情页跳转
        if(router.getParams().sourcePage && router.getParams().sourcePage === 'groupChatMessage'){
            this.uid=router.getParams().groupMemberId;
            this.person.name=router.getParams().groupMemberId;
            this.person.uid=router.getParams().groupMemberId;
            this.$app.$def.mailFriendId=router.getParams().sayOrGroup_ID
        }
        else if(router.getParams().sayOrGroup === 'group' && this.mailFriendId !== -1){
            //通讯录跳转
            this.person.imgUrl = this.$app.$def.groupList[this.mailFriendId].imgUrl
            this.person.name = this.$app.$def.groupList[this.mailFriendId].text
            this.uid = this.$app.$def.groupList[this.mailFriendId].text
        }else if(router.getParams().sayOrGroup === 'group' && this.mailFriendId == -1){
            this.person.imgUrl = this.$app.$def.chatData[this.idx].imgUrl;
            this.person.name = this.$app.$def.chatData[this.idx].title;
        } else if(this.mailFriendId == -1){
            this.person.imgUrl = this.$app.$def.chatData[this.idx].imgUrl;
            this.person.name = this.$app.$def.chatData[this.idx].title;
        }else{
            //通讯录跳转
            this.person.imgUrl = this.$app.$def.friendsList[this.mailFriendId].imgUrl
            this.person.name = this.$app.$def.friendsList[this.mailFriendId].text
            this.uid = this.$app.$def.friendsList[this.mailFriendId].text
        }
    },
    onCreate() {
        this.uid = this.$app.$def.uid
    },
    onShow() {
        console.info("friendDetail=====>onShow()");
        this.inBlackListOrNot();
    },
    /*获取部分权限*/
    grantPermission() {
        console.info('friendDetail=====>grantPermission')
        let context = featureAbility.getContext()
        context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) {
            console.info(`friendDetail=====>grantPermission,requestPermissionsFromUser`)
        })
    },
    showDialog(e) {
        if(e == 3){
            this.eIdx = e;
            this.$element('simpledialog').show()
        }
    },
    cancelDialog(e) {
        prompt.showToast({
            message: 'Dialog cancelled'
        })
    },
    cancelSchedule(e) {
        this.$element('simpledialog').close()
        prompt.showToast({
            message: 'Successfully cancelled'
        })
    },
    // 点击事件
    deleteFriend(){
        prompt.showToast({
            message: '开始删除！'+ this.eIdx,
            duration: 2000,
        });
        if(this.eIdx == 3){
            console.info('deleteFriend====>e==3');
            let httpRequest = http.createHttp();
            httpRequest.request(
                "http://" + this.$app.$def.ip + "/user/deleteFriend",
                {
                    method: 'POST',
                    extraData:JSON.stringify({"uid":this.$app.$def.uid,"touid": this.uid}),
                    connectTimeout: 30000,
                    readTimeout: 60000,
                    header: {
                        'Content-Type': 'application/json'
                    }
                },(err, data) => {
                console.info('friendDetail====>deleteFriend'+data.result.toString());
                if (!err) {
                    let re = JSON.parse(data.result.toString())
                    // code : 200 表示成功
                    if(re.code == '200'){
                        prompt.showToast({
                            message: '删除成功！',
                            duration: 2000,
                        });
                        this.$app.$def.chatData.splice(this.idx,1)
                        router.push({
                            uri: "pages/index/index",
                        });
                    }else {
                        prompt.showToast({
                            message: '删除失败！',
                            duration: 2000,
                        });
                    }
                } else {
                    httpRequest.destroy();
                }
            });
        }
    },
    backToSession(){
        this.$app.$def.mailFriendId = -1;
        router.back();
    },
    sendMessage(e){
        if(e == 0){
            console.info("friendDetail=====>sendMessage sayOrGroup_ID:"+router.getParams().sayOrGroup_ID)
            router.push({
                uri: "pages/dialogPage/dialogPage",
                params: {
                    sayOrGroup: router.getParams().sayOrGroup,
                    sayOrGroup_ID: router.getParams().sayOrGroup_ID,
                }
            });
        }
    },
    //判断该联系人是否在黑名单
    inBlackListOrNot(){
        console.info('friendDetail=====>friend 1ID:' + this.uid)
        console.info('friendDetail=====>friend 2ID:' + this.person.name)
        let httpRequest= http.createHttp();
        let promise = httpRequest.request("http://" + this.$app.$def.ip +"/user/isInBlacklist", {
            method: 'POST',
            extraData:JSON.stringify({"uid":this.$app.$def.uid,"blockedUid":this.uid}),
            connectTimeout: 60000,
            readTimeout: 60000,
            header: {
                'Content-Type': 'application/json'
            }
        });
        console.info("friendDetail=====>uid:"+this.$app.$def.uid+"  blockedUid:"+this.uid)
        promise.then((res) => {
            let re = JSON.parse(res.result.toString())
            console.info('friendDetail=====>inBlackListOrNot()'+re.toString())
            if(re.code == 2033) {
                this.inBlackList=true;
                prompt.showToast({
                    message: '黑名单信息获取成功，在',
                    duration: 2000,
                });
            }
            else if(re.code == 2034) {
                this.inBlackList=false;
                prompt.showToast({
                    message: '黑名单信息获取成功，不在',
                    duration: 2000,
                });
            }
        }).catch(() => {
            console.info('friendDetail=====>inBlackListOrNot1:err');
            prompt.showToast({
                message: '获取黑名单信息失败',
                duration: 2000,
            });
            console.info('friendDetail=====>inBlackListOrNot2:err');
        });
        httpRequest.destroy();
    },
    //切换联系人黑名单状态
    switchBlackListStatus(){
        if(this.inBlackList===true){
            console.info('friendDetail=====>remove ID:' + this.uid)
            let httpRequest= http.createHttp();
            let promise = httpRequest.request("http://" + this.$app.$def.ip +"/user/deleteFromBlacklist/", {
                method: 'POST',
                extraData:JSON.stringify({"uid":this.$app.$def.uid,"blockedUid":this.uid}),
                connectTimeout: 60000,
                readTimeout: 60000,
                header: {
                    'Content-Type': 'application/json'
                }
            });
            promise.then((res) => {
                let re = JSON.parse(res.result.toString())
                console.info(res.toString())
                if(re.code == 2037) {
                    this.inBlackList=false
                    prompt.showToast({
                        message: '已将联系人移出黑名单',
                        duration: 2000,
                    });
                }
                else if(re.code == 2038) {
                    this.inBlackList=true
                    prompt.showToast({
                        message: '联系人移出黑名单失败,逻辑',
                        duration: 2000,
                    });
                }
            }).catch(() => {
                console.info('friendDetail=====>remove1:err');
                prompt.showToast({
                    message: '联系人移出黑名单失败,网络',
                    duration: 2000,
                });
                this.inBlackList=true
                console.info('friendDetail=====>remove2:err');
            });
            httpRequest.destroy();
        }
        else if(this.inBlackList===false){
            console.info('addBlackList ID:' + this.uid)
            let httpRequest= http.createHttp();
            let promise = httpRequest.request("http://" + this.$app.$def.ip +"/user/addToBlacklist", {
                method: 'POST',
                extraData:JSON.stringify({"uid":this.$app.$def.uid,"blockedUid":this.uid}),
                connectTimeout: 60000,
                readTimeout: 60000,
                header: {
                    'Content-Type': 'application/json'
                }
            });
            promise.then((res) => {
                let re = JSON.parse(res.result.toString())
                if(re.code == 2035) {
                    this.inBlackList=true;
                    prompt.showToast({
                        message: '已将联系人移入黑名单',
                        duration: 2000,
                    });
                }
                else if(re.code == 2036) {
                    this.inBlackList=false;
                    prompt.showToast({
                        message: '联系人移入黑名单失败,逻辑',
                        duration: 2000,
                    });
                }
            }).catch(() => {
                console.info('friendDetail=====>inBlackList1'+this.inBlackList);
                this.inBlackList=false;
                console.info('friendDetail=====>inBlackList2'+this.inBlackList);
                console.info('friendDetail=====>add1:err');
                prompt.showToast({
                    message: '联系人移入黑名单失败,断联',
                    duration: 2000,
                });
                console.info('friendDetail=====>add2:err');
            });
            httpRequest.destroy();
        }
        else{
            console.info('blackList status undefined')
        }
    }
}



